package com.example.filter;

import com.example.utils.CurrentHolder;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;

import java.io.IOException;

/**
 * @Auther: Sun
 * @Date: 2025/9/24 - 09 - 24 - 9:35
 * @Description: com.example.filter
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String request1 = request.getRequestURI();
        if (request1.contains("/login")){
            log.info("登陆操作");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader("token");
        if (token==null|| token.isEmpty()){
            log.info("令牌为空,响应401状态码");
            response.setStatus(401);
            response.getWriter().write("用户未登录，请先登录");
            return;
        }

        try {
           Claims claims = JwtUtils.parseJWT(token);
          Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前登录员工ID：{}，将其存入ThreadLocal",empId);
        } catch (Exception e) {
            log.info("令牌非法,响应401状态码");
            response.setStatus(401);
            return;
        }
        log.info("令牌合法,放行");
        filterChain.doFilter(servletRequest,servletResponse);
        //清除ThreadLocal中的数据
        CurrentHolder.remove();
    }
}
